package com.letv.whatslive.mongo.dao;

import com.google.common.collect.Lists;
import com.letv.whatslive.common.utils.DateUtils;
import com.letv.whatslive.common.utils.ObjectUtils;
import com.letv.whatslive.model.ActivityCategory;
import com.letv.whatslive.model.convert.ActivityCategoryConvert;
import com.letv.whatslive.model.utils.ObjUtils;
import com.letv.whatslive.mongo.BaseDAO;
import com.letv.whatslive.redis.JedisDAO;
import com.mongodb.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * Created by Administrator on 2016/3/7.
 */
@Repository
public class ActivityCategoryDAO extends BaseDAO{
    private final static Logger logger = LoggerFactory.getLogger(ActivityCategoryDAO.class);

    protected String collectionName = "activityCategory";

    @Autowired
    protected JedisDAO jedisDAO;

    @Override
    protected void init() {
        super.init(this.collectionName);
    }

    @Override
    protected long getAutoIncrementId() {
        return idGenerate.generateId(this.collectionName);
    }


    /**
     * 查询用户列表
     *
     * @param params 模糊查询的查询条件
     * @param orders 排序的条件
     * @param start  查询条件的开始分页数
     * @param limit  查询条件的分页每页条数
     * @return
     */
    public List<ActivityCategory> getActivityCategoryListByParams(Map<String, Object> params, Map<String, Object> orders, Integer start, Integer limit) {

        List<ActivityCategory> result = Lists.newArrayList();
        if (limit == null) {
            limit = DEFAULT_NUM;
        }
        //TODO 临时用于检查错误用户数据
        ActivityCategory errorActivityCategory = new ActivityCategory();
        try {
            //dbObj 类似于 mysql 查询中的 where 关键字，可以添加各种搜索条件
            BasicDBObject order = getOrderParams(orders);
            BasicDBObject query = getBasicDBObjectByParams(params);
            Integer skip = start == null ? 0 : start;
            DBCursor cur = this.dbCollection.find(query).skip(skip).sort(order).limit(limit);//按createTime的值倒叙排列
            while (cur.hasNext()) {
                DBObject dbObject = cur.next();
                ActivityCategory activityCategory = ActivityCategoryConvert.castDBObjectToActivityCategory(dbObject);
                errorActivityCategory = activityCategory;
                result.add(activityCategory);
            }
        } catch (Exception e) {
            logger.error("uid:<"+errorActivityCategory.getId()+"> error:<"+e.getMessage()+">",e);
        }
        return result;
    }

    public List<ActivityCategory> getAllActivityCategoryByParams(Map<String, Object> params){
        List<ActivityCategory> result = Lists.newArrayList();
        try {
            //dbObj 类似于 mysql 查询中的 where 关键字，可以添加各种搜索条件
            BasicDBObject query = getBasicDBObjectByParams(params);
            DBCursor cur = this.dbCollection.find(query);
            while (cur.hasNext()) {
                DBObject dbObject = cur.next();
                ActivityCategory activityCategory = ActivityCategoryConvert.castDBObjectToActivityCategory(dbObject);
                result.add(activityCategory);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     * 根据主键查询一个用户
     * @param categoryId 用户主键
     * @return 一个ActivityCategory对象
     */
    public ActivityCategory getActivityCategoryById(Long id) {
        BasicDBObject query = new BasicDBObject();
        ActivityCategory activityCategory = new ActivityCategory();
        query.put("_id", id);
        DBObject dbObject = this.dbCollection.findOne(query);
        if (dbObject == null) return null;
        try {
            activityCategory = ActivityCategoryConvert.castDBObjectToActivityCategory(dbObject);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return activityCategory;
    }


    /**
     * 查询用户的数量
     * @param params 查询条件参数
     * @return 满足条件的文档记录数
     */
    public Long countActivityCategoryByParams(Map params) {
        //dbObj 类似于 mysql 查询中的 where 关键字，可以添加各种搜索条件
        BasicDBObject query = getBasicDBObjectByParams(params);
        return this.dbCollection.count(query);
    }

    /**
     * 保存用户信息
     * @param activityCategory
     * @return
     */
    public ActivityCategory saveActivityCategory(ActivityCategory activityCategory) {
        try {
            activityCategory.setId(getAutoIncrementId());
            DBObject dbo = ActivityCategoryConvert.castActivityCategoryToDBObject(activityCategory);
            WriteResult wr = this.dbCollection.insert(dbo);
            return activityCategory;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return null;
        }
    }

    /**
     * 更新用户基本信息
     * @param ActivityCategory
     */
    public void updateActivityCategory(ActivityCategory ActivityCategory) {
        DBObject queryCondition = new BasicDBObject();
        Long id = ActivityCategory.getId();
        queryCondition.put("_id", id); // 用来确定要修改的文档
        DBObject setValue = ActivityCategoryConvert.castActivityCategoryToDBObject(ActivityCategory);
        //剔除主键修改
        if (setValue.containsKey("_id")) {
            setValue.removeField("_id");
        }
        DBObject values = new BasicDBObject("$set", setValue);
        this.dbCollection.update(queryCondition, values, false, false);
    }

    /**
     * 根据用户ID删除用户
     * @param uid
     */
    public void deleteActivityCategory(Long uid){
        BasicDBObject query = new BasicDBObject();
        query.put("_id", uid);
        this.dbCollection.remove(query);
    }

    /**
     * 获取排序的BasicDBObject对象
     * @param orders
     * @return
     */
    private BasicDBObject getOrderParams(Map<String, Object> orders) {
        BasicDBObject order = new BasicDBObject();
        if(null != orders &&orders.size()>0){
            for(String key : orders.keySet()){
                order.append(key, Integer.valueOf(String.valueOf(orders.get(key))));
            }
        }else{
            //默认按照创建时间排序
            order.append("_id", -1);
        }
        return order;
    }

    /**
     * 根据查询参数Map获取查询条件对象
     * @param params 查询参数Map
     * @return
     */
    private BasicDBObject getBasicDBObjectByParams(Map params){
        //dbObj 类似于 mysql 查询中的 where 关键字，可以添加各种搜索条件
        BasicDBObject query = new BasicDBObject();// 新建查询基类对象 dbo
        if (params != null && params.size() > 0) {
            if (params.get("_id") != null) {
                query.put("_id", ObjectUtils.toLong(params.get("_id")));
            }
            if (params.get("categoryCode") != null) {
                query.put("categoryCode", ObjectUtils.toString(params.get("categoryCode")));
            }
            if (params.get("categoryUpCode") != null) {
                query.put("categoryUpCode", ObjectUtils.toString(params.get("categoryUpCode")));
            }
            if (params.get("categoryName") != null) {
                Pattern pattern = Pattern.compile("^.*" + params.get("categoryName") + ".*$", Pattern.CASE_INSENSITIVE);
                query.put("categoryName", pattern);
            }

        }
        return query;
    }



    public List<Long> getActivityCategoryIdsByParams(Map<String, Object> params, Map<String, Object> orders) {

        List<Long> result = Lists.newArrayList();

        try {

            BasicDBObject query = getBasicDBObjectByParams(params);
            BasicDBObject order = getOrderParams(orders);
            DBCursor cur = this.dbCollection.find(query).sort(order);
            while (cur.hasNext()) {
                DBObject dbObject = cur.next();
                result.add(ObjUtils.toLong(dbObject.get("categoryId")));
            }
        } catch (Exception e) {

            logger.error("getActivityCategoryIdsByParams error", e);
        }

        return result;
    }


}
